from sqlalchemy import func

from app.models import db


class Ticket(db.Model):
    __tablename__: str = 'ticket'

    id = db.Column(db.Integer, primary_key=True)
    seat_no = db.Column(db.String(120))
    seat_class = db.Column(db.String(120))
    price = db.Column(db.Numeric(8, 2))
    state = db.Column(db.Integer, default=0)
    train_no = db.Column(db.String(120), db.ForeignKey('train.train_no'), nullable=False, index=True)
    passenger_id = db.Column(db.Integer, db.ForeignKey('passenger.id'), nullable=False, index=True)
    order_id = db.Column(db.Integer, db.ForeignKey('order.id'), nullable=False, index=True)
    from_station = db.Column(db.String(120))
    to_station = db.Column(db.String(120))
    date = db.Column(db.String(120))
    departure_time = db.Column(db.DateTime)
    arrival_time = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=func.now())
    updated_at = db.Column(db.DateTime, default=func.now())
    order = db.relationship('Order', backref=db.backref('tickets'))
    passenger = db.relationship('Passenger', backref=db.backref('tickets'))

    def __repr__(self):
        return f'<Ticket {self.id}>'

    def updateState(self):
        self.state = 1
        return self

    @classmethod
    def generateTicket(cls, item, passenger_id):
        # Create a new Ticket object
        ticket = Ticket(
            seat_class=item["seatClass"],
            train_no=item["trainNo"],
            from_station=item["from"],
            to_station=item["to"],
            date=item["date"],
            passenger_id=passenger_id
        )
        return ticket
